package nc.bs.arap.busireg;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import nc.bs.businessevent.BdUpdateEvent;
import nc.bs.businessevent.BusinessEvent;
import nc.bs.businessevent.IBusinessEvent;
import nc.bs.businessevent.IBusinessListener;
import nc.util.sip.JdbcUtil;
import nc.vo.arap.basebill.BaseAggVO;
import nc.vo.arap.utils.ArrayUtil;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @Description //TODO 删除前校验，如果被客开单据引用则不允许删除
 * @Author CYQ
 * @Date 2025/6/19 12:17
 * @Param
 * @return
 **/
public class BillDeleteCheckListener implements IBusinessListener {
    @Override
    public void doAction(IBusinessEvent event) throws BusinessException {
        BaseAggVO[] bills = this.getBills(event);
        //拼接所有收款单主键
        String insql = Arrays.asList(bills).stream().map(v->v.getPrimaryKey()).collect(Collectors.joining(",","'","'"));
        //查询能关联上的培训单据编码
        String code = JdbcUtil.queryColumn("select h.code from ARAP_TRAIN_B b left join ARAP_TRAIN h on h.PK_TRAIN=b.PK_TRAIN where srcbillid in ("+insql+") and nvl(h.dr,0)=0 and nvl(b.dr,0)=0");
        if(!ObjectUtil.isEmpty(code))
            throw new BusinessException("收款单已被培训单据["+code+"]引用,禁止删除!");
    }
    private BaseAggVO[] getBills(IBusinessEvent event) {
        Object value = null;
        if (event instanceof BusinessEvent) {
            value = ((BusinessEvent)event).getObject();
        }
        BaseAggVO[] bills = null;
        if (null != value) {
            if (value.getClass().isArray()) {
                Object[] objs = (Object[])value;
                bills = objs instanceof BaseAggVO[] ? (BaseAggVO[])objs : (BaseAggVO[]) ArrayUtil.convertSupers2Subs((AggregatedValueObject[])objs, BaseAggVO.class);
            } else {
                bills = new BaseAggVO[]{(BaseAggVO)value};
            }
        }
        return bills;
    }
}
